package com.tommy.store;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tommy.store.file.FileDownloader;
import com.tommy.store.file.SqliteDemo;
import com.tommy.store.http.HttpClient;
import com.tommy.store.http.MyHttpGet;
import com.tommy.store.http.MyHttpPut;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

@RestController
@RequestMapping("/main")
public class MainController {
    @Autowired
    NamedParameterJdbcTemplate jdbcTemplate;

    // private static final ThreadLocal<String> token_local = new ThreadLocal<>();

    @RequestMapping("/")
    String hello() {
        return "Hello main!";
    }

    // 创建HttpClient对象
    static CloseableHttpClient httpClient = HttpClients.createDefault();
    static String bearerToken = "eyJraWQiOiJLcU8iLCJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzMmJhZjQzYmRiNmE0Mzg4OGY0NGMwNzU3NzYyNmQzNyIsImF1ZCI6IjNkOWQ3Zjk5ZTU2NjQ3YWI4ZmFkOTVlYTg3MTNhZTI4IiwicyI6ImNkYSIsImQiOiIyMzA4MzAwOTAsNzU3NzU5MDkyIiwiaXNzIjoiYWxpcGFuIiwiZXhwIjoxNzI5NTA1NzE1LCJpYXQiOjE3Mjk0OTg1MTIsImp0aSI6IjIzM2EwNWNhYTZjZTQwNmQ4N2UzNTQzMDA4MjdhNDc2In0.HvmgiybfR9PqAjPkooMefZvpeZqe4pijHnuPbOLs9dE";
    static String drive_id = "230830090";

    // access_token
    @RequestMapping("/access_token")
    String access_token(@RequestBody String body) {
        JSONObject bodyObj = JSONObject.fromObject(body);
        String code = bodyObj.getString("code");

        String bodyStr = "{   \r\n" + //
                "  \"client_id\": \"3d9d7f99e56647ab8fad95ea8713ae28\",    \r\n" + //
                "  \"client_secret\": \"52a9cf17de244dbd8bf5d2e54e45bd08\",     \r\n" + //
                "  \"grant_type\": \"authorization_code\",   \r\n" + //
                "  \"code\": \"" + code + "\"\r\n" + //
                "}";
        String result = HttpClient.request("access_token", bodyStr, null);

        JSONObject paramsObj = JSONObject.fromObject(result);
        if (paramsObj.has("access_token")) {
            bearerToken = paramsObj.getString("access_token");
        } else {
            bearerToken = "";
        }
        return "{\"token\": \"" + bearerToken + "\"}";
    }

    // 用户信息
    @RequestMapping("/get_token")
    String get_token() {
        return bearerToken;
    }

    // 用户信息
    @RequestMapping("/users_info")
    String users_info() {
        String result = HttpClient.request("users_info", null, bearerToken);
        return result;
    }

    // 设备信息
    @RequestMapping("/user_getDriveInfo")
    String user_getDriveInfo() {
        String bodyStr = "{}";
        String result = HttpClient.request("user_getDriveInfo", bodyStr, bearerToken);
        return result;
    }

    // 文件列表
    @RequestMapping("/openFile_list")
    String openFile_list(@RequestBody String body) {
        JSONObject bodyObj = JSONObject.fromObject(body);
        String parent_file_id = "root";
        if (bodyObj.has("parent_file_id")) {
            parent_file_id = bodyObj.getString("parent_file_id");
        }
        String bodyStr = "{\r\n" + //
                "    \"drive_id\": \"" + drive_id + "\",\r\n" + //
                "    \"parent_file_id\": \"" + parent_file_id + "\"\r\n" + //
                "}";
        String result = HttpClient.request("openFile_list", bodyStr, bearerToken);
        return result;
    }

    // 文件详情
    @RequestMapping("/openFile_get")
    String openFile_get(@RequestBody String body) {
        JSONObject bodyObj = JSONObject.fromObject(body);
        String file_id = bodyObj.getString("file_id");
        String bodyStr = "{\r\n" + //
                "    \"drive_id\": \"" + drive_id + "\",\r\n" + //
                "    \"file_id\": \"" + file_id + "\"\r\n" + //
                "}";
        String result = HttpClient.request("openFile_get", bodyStr, bearerToken);
        return result;
    }

    // 下载链接
    @RequestMapping("/openFile_getDownloadUrl")
    String openFile_getDownloadUrl(@RequestBody String body) {
        JSONObject bodyObj = JSONObject.fromObject(body);
        String file_id = bodyObj.getString("file_id");
        String bodyStr = "{\r\n" + //
                "    \"drive_id\": \"" + drive_id + "\",\r\n" + //
                "    \"file_id\": \"" + file_id + "\"\r\n" + //
                "}";
        String result = HttpClient.request("openFile_getDownloadUrl", bodyStr, bearerToken);
        return result;
    }

    // 下载文件，通过接口返回Blob或json，为mate-parser提供
    @RequestMapping("/getFile")
    ResponseEntity<Resource> getFile(@RequestBody String body) throws Exception {
        JSONObject bodyObj = JSONObject.fromObject(body);
        String remoteFilePath = bodyObj.getString("url");
        String name = bodyObj.getString("name");
        String mime_type = bodyObj.getString("mime_type");

        String localFilePath = System.getProperty("user.home") + "/" + name; // 本地文件路径，存储在用户根目录下
        String downloadResult = FileDownloader.downloadFile(remoteFilePath, localFilePath);
        // SqliteDemo.loadDatabase();
        if (downloadResult != "success") {
            return ResponseEntity.status(500).body(null);
        }

        // 假设你的文件位于项目的static目录下
        Path filePath = Paths.get(localFilePath);
        Resource resource = new UrlResource(filePath.toUri());

        if (resource.exists() || resource.isReadable()) {
            return ResponseEntity.ok()
                    .contentType(MediaType.valueOf(mime_type))
                    .header("Content-Disposition", "attachment; filename=\"" + name + "\"")
                    .body(resource);
        } else {
            // 文件未找到，你可以返回404或其他错误状态
            return null;
        }

    }

    // 下载文件，通过接口返回Blob或json，为mate-boot提供
    @RequestMapping("/getFileContent")
    ResponseEntity getFileContent(@RequestBody String body) throws Exception {
        JSONObject bodyObj = JSONObject.fromObject(body);
        String remoteFilePath = bodyObj.getString("url");
        String name = bodyObj.getString("name");
        String mime_type = bodyObj.getString("mime_type");
        // Resource resource = new UrlResource(new URI(remoteFilePath));

        ResponseEntity result = MyHttpGet.downloadFile(remoteFilePath, name);

        return result;

    }

    // 加载文件
    @RequestMapping("/loadFile")
    String loadFile(@RequestBody String body) {
        JSONObject bodyObj = JSONObject.fromObject(body);
        String file_id = bodyObj.getString("file_id");
        String bodyStr = "{\r\n" + //
                "    \"drive_id\": \"" + drive_id + "\",\r\n" + //
                "    \"file_id\": \"" + file_id + "\"\r\n" + //
                "}";
        String result = HttpClient.request("openFile_getDownloadUrl", bodyStr, bearerToken);

        JSONObject paramsObj = JSONObject.fromObject(result);
        if (paramsObj.has("url")) {
            String remoteFilePath = paramsObj.getString("url");
            String localFilePath = System.getProperty("user.home") + "/lowcode_data.db"; // 本地文件路径，存储在用户根目录下
            FileDownloader.downloadFile(remoteFilePath, localFilePath);
            SqliteDemo.loadDatabase();
            return "success";
        }

        return "failure";
    }

    // 创建文件
    @RequestMapping("/createFile")
    String createFile(@RequestBody String body) {
        String final_result = "";

        JSONObject bodyObj = JSONObject.fromObject(body);
        String parent_file_id = bodyObj.getString("parent_file_id");
        String name = bodyObj.getString("name");
        String content = bodyObj.getString("content");
        String bodyStr = "{\r\n" + //
                "    \"drive_id\": \"" + drive_id + "\",\r\n" + //
                "    \"parent_file_id\": \"" + parent_file_id + "\",\r\n" + //
                "    \"name\": \"" + name + "\",\r\n" + //
                "    \"type\": \"file\",\r\n" + //
                "    \"check_name_mode\": \"auto_rename\"\r\n" + //
                "}";
        String result_1 = HttpClient.request("openFile_create", bodyStr, bearerToken);

        JSONObject paramsObj = JSONObject.fromObject(result_1);
        if (paramsObj.has("upload_id")) {
            String file_id = paramsObj.getString("file_id");
            String upload_id = paramsObj.getString("upload_id");
            JSONArray part_info_list = paramsObj.getJSONArray("part_info_list");
            JSONObject part_info = (JSONObject) part_info_list.get(0);
            if (part_info.has("upload_url")) {
                String upload_url = part_info.getString("upload_url");
                String result_2 = MyHttpPut.request(upload_url, name, content);

                String completeBody = "{\r\n" + //
                        "    \"drive_id\": \"" + drive_id + "\",\r\n" + //
                        "    \"file_id\": \"" + file_id + "\",\r\n" + //
                        "    \"upload_id\": \"" + upload_id + "\"\r\n" + //
                        "}";

                final_result = HttpClient.request("openFile_complete", completeBody, bearerToken);
                return final_result;
            }
        } else {
            final_result = result_1;
        }

        return final_result;
    }

    // 查询数据
    @RequestMapping("/queryData")
    String queryData(@RequestBody String body) {

        JdbcTemplate jdbcTemplate = new JdbcTemplate(SqliteDemo.dataSource);

        String sql = "select * from comment_info";

        List<Map<String, Object>> aaa = jdbcTemplate.queryForList(sql);

        String result = JSONArray.fromObject(aaa).toString();

        return result;
    }
}
